package com.bsc.rtc.lib.libraries.RetrofitNet.download;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.bsc.rtc.lib.libraries.Constant;
import com.bsc.rtc.lib.libraries.R;

import java.io.File;

public class DownApkService extends Service {
    NotificationManager mNotificationManager;
    RemoteViews view;
    Notification notification;
    int notifyid = 30001; //自己设置就好


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String url = intent.getStringExtra(Constant.ER_MAO_APK_DOWN_URL);

        if (url != null) {
            initNotification();
            downLoadApk(url);
        } else {
            Log.e("DownApkService", "down url =null");
        }

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("DownApkService", "onDestroy ");
    }

    /**
     * @auth zzw
     * @Date 2019/8/2 15:46
     * @Desc 初始话Notification
     */
    private void initNotification() {
        String channelid = "com.czz.downloadapk";
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            //android8.0 增加了渠道，如果不设置，在8.0下是无法显示通知的,channelid自己定义就好,渠道名会显示在系统设置-app的通知管理下
            NotificationChannel Channe = new NotificationChannel(channelid,
                    "下载服务", NotificationManager.IMPORTANCE_HIGH);
            mNotificationManager.createNotificationChannel(Channe);
        }
        //写一个带ProgressBar和TextView的layout
        //创建 RemoteViews下面用来更新进度
        view = new RemoteViews(getPackageName(), R.layout.item_loading_view);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, getPackageName());
        builder.setContentText("正在下载二猫")
                .setContentTitle("正在下载")
                .setChannelId(channelid)//直接加上channelid
                .setDefaults(NotificationCompat.DEFAULT_VIBRATE) //悬浮通知设置
                .setPriority(NotificationCompat.PRIORITY_MAX)  //悬浮通知设置
                .setCustomContentView(view)
                .setSmallIcon(R.mipmap.ic_launcher);
        notification = builder.build();
        notification.flags = Notification.FLAG_ONGOING_EVENT;//设置通知栏常驻
        mNotificationManager.notify(notifyid, notification); //发送通知
    }

    /**
     * @auth zzw
     * @Date 2019/8/2 15:44
     * @Desc 下载apk
     */
    private void downLoadApk(String downUrl) {
        final File file = new File(Environment.getExternalStorageDirectory().getPath() + "ermao.apk");
        if (!file.exists()) {
            file.mkdir();
        }
        DownloadUtil.download(downUrl, Environment.getExternalStorageDirectory().getPath() + "/test.apk", new DownloadListener() {
            @Override
            public void onStart() {
                Log.i("DownApkService", "downLoad onStart ");
                view.setProgressBar(R.id.loading_progress, 100, 0, false);
            }

            @Override
            public void onProgress(int progress) {
             //   int result = (int) ((bytesRead * 100) / contentLength);//进度
                Log.i("DownApkService", "downLoad result " + progress);
                //设置进度条
                view.setProgressBar(R.id.loading_progress, 100, progress, false);
                mNotificationManager.notify(notifyid, notification);//更新进度条
            }

            @Override
            public void onFinish(String path) {
                Log.i("DownApkService", "downLoad path " + path);
                //install(path, context);
                sendDownFinishBrocast(path);
                stopSelf();//下载完成关闭自己
            }

            @Override
            public void onFail(String errorInfo) {
                Log.e("DownApkService", "downLoad apk err " + errorInfo);
            }
        });
        /*
        XHttp.downLoad(downUrl)
                .savePath(Environment.getExternalStorageDirectory().getPath())
                .saveName("ermao.apk")
                .execute(new DownloadProgressCallBack<String>() {
                    @Override
                    public void onStart() {
                        Log.i("DownApkService", "downLoad onStart ");
                        view.setProgressBar(R.id.loading_progress, 100, 0, false);

                    }

                    @Override
                    public void onError(ApiException e) {
                        Log.e("DownApkService", "downLoad apk err " + e.getDetailMessage());
                    }

                    @Override
                    public void update(final long bytesRead, final long contentLength, boolean done) {


                        int result = (int) ((bytesRead * 100) / contentLength);//进度
                        Log.i("DownApkService", "downLoad result " + result);
                        //设置进度条
                        view.setProgressBar(R.id.loading_progress, 100, result, false);
                        mNotificationManager.notify(notifyid, notification);//更新进度条


                    }

                    @Override
                    public void onComplete(String path) {
                        LogHelper.SimpleLog("path", path);
                        Log.i("DownApkService", "downLoad path " + path);
                        //install(path, context);
                        sendDownFinishBrocast(path);
                        stopSelf();//下载完成关闭自己
                    }
                });*/
    }

    /**
     * @auth zzw
     * @Date 2019/8/2 16:15
     * @Desc 发送下载完成广播
     */
    private void sendDownFinishBrocast(String path) {
/*        Intent intent = new Intent(Constant.ER_MAO_APK_DOWN_FINISH);
        intent.putExtra(Constant.ER_MAO_APK_SAVE_PATH, path);
        sendBroadcast(intent);*/
    }
}
